#include "StompedReality/Asset/AnimationManager.h"
#include "StompedReality/Components/JointComponent.h"
#include "StompedReality/Core.h"
#include "StompedReality/Core/FileSystem.h"
#include "StompedReality/Core/IGame.h"
#include "StompedReality/Core/TypeSystem/TypeSystem.h"
namespace StompedReality
{
namespace animation
{
AnimationManager::AnimationManager ( ) :
  StompedReality::GameAccess( )
{
  this->_jointAnimations = 0;
}

AnimationManager::~AnimationManager( )
{
  delete[] this->_jointAnimations;
}

void AnimationManager::Initialize ( int capacity )
{
  if ( this->_jointAnimations != 0 )
    delete[] this->_jointAnimations;
#ifdef DEBUG
  std::cout << "info\t[AnimationManager]\t[initialize]\tcapacity: " << capacity << std::endl;
#endif
  this->_jointAnimations = new JointAnimation[capacity];
}

JointAnimation* AnimationManager::getJointAnimation ( StompedReality::ID id )
{
  return this->_jointAnimations + id;
}

bool AnimationManager::ParseConfig ( Json::Value& root )
{
#ifdef DEBUG
  std::cout << "info\t[AnimationManager]\t[parseJSON]\tfield: AnimationManager" << std::endl;
#endif
  this->Initialize ( root["AnimationManager"].get ( "capacity", 512 ).asInt( ) );
  return true;
}

bool AnimationManager::ReadFromFile ( const char* fileName )
{
#ifdef DEBUG
  std::cout << "info\t[AnimationManager]\t[readAnimations]\tfield: JointAnimations" << std::endl;
#endif
  Json::Value root = *(this->m_Game->getFileSystem( )->openAsJson ( fileName ));
  StompedReality::type_system::TypeInfo* jointAnimType =
    StompedReality::type_system::TypeSystem::GetType<StompedReality::animation::JointAnimation>( );
  for ( unsigned i = 0; i < root["JointAnimations"].size( ); ++i )
  {
    int id =  root["JointAnimations"][i].get ( "id", -1 ).asInt( );
    if ( id == -1 )
      continue;
    jointAnimType->read ( root["JointAnimations"][i]["animation"],
                          ( char* ) this->getJointAnimation ( id ) );
#ifdef DEBUG
    std::cout << "info\t[AnimationManager]\t[readAnimations]\tAnimation ID: " << id <<
    ", Frames:" << this->getJointAnimation ( id )->numberOfFrames( ) << std::endl;
#endif
  }
  return true;
}

}
}
